package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class MyAspect {
    //AOP编程将重复的代码抽取到切面类中 用反射获取参数
    @Before("execution(* com.sky.mapper.*.*(..))&&@annotation(com.sky.annotation.AutoFill)")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始填充");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//强制转换为这个子类才能获取方法签名上面的注解
        Method method = signature.getMethod();
        AutoFill autoFill = method.getAnnotation(AutoFill.class);
        OperationType op=autoFill.value();
        Object[] args=joinPoint.getArgs();
        if(args==null||args.length==0){
            return;
        }
        Object object=args[0];
        try {
            Method m1=object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method m2=object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method m3=object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method m4=object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            if(op==OperationType.INSERT){
                m1.invoke(object, LocalDateTime.now());
                m2.invoke(object, LocalDateTime.now());
                m3.invoke(object, BaseContext.getCurrentId());
                m4.invoke(object,BaseContext.getCurrentId());
            }
            else{
                m2.invoke(object,LocalDateTime.now());
                m4.invoke(object,BaseContext.getCurrentId());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
